﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IRC.IRepairClouds.DataLayer.Cache
{
    public abstract class DataCachedLoader<TC> where TC : class
    {
        private WeakReference<TC> _cached;
        private object _sync = new object();
        private bool _isnull = false;

        protected abstract TC Load();

        public bool IsLoaded
        {
            get { return _cached != null && _cached.IsAlive; }
        }

        public TC Cached
        {
            get
            {
                if (_isnull)
                    return null;
                TC res;
                if (_cached == null || (res = _cached.Target) == null) {
                    lock (_sync) {
                        if (_cached == null || (res = _cached.Target) == null) {
                            res = Load();
                            if (res != null)
                                _cached = new WeakReference<TC>(res);
                            else {
                                _isnull = true;
                                //TODO: log
                            }
                        }
                    }
                }
                return res;
            }
        }
    }
}
